import React, { useState, useEffect, useMemo } from 'react';
import './index.less';
import CommonHead from '@/components/CommonHead/CommonHead';
import { getItems } from '@/api'
import { useSearchParams, useNavigate } from 'umi';
import Items from './components/Items'
export default function Page() {
  const [searchParams] = useSearchParams();
  const navigate = useNavigate();
  // 定义状态 改变 高亮类
  const [orderStatus, setOrderStatus] = useState({
    orderIndex: 0, // 0销量1价格2新品
    upDown: 0 // 0升序 1 降序
  })
  const order = useMemo(() => {
    let _order = 'ordersDown';
    switch (orderStatus.orderIndex) {
      case 0:
        _order = 'ordersDown';
        break;
      case 1: 
        if (orderStatus.upDown === 0) {
          _order = 'priceUp'
        } else {
          _order = 'priceDown'
        }
        break;
      case 2:
        _order = 'addedDown';
        break;

      default:
        break;
    }
    return _order
  }, [orderStatus])
  // 点击按照 非价格排序 （销量或新品）
  const orderHandler = (orderIndex: number) => {
    setOrderStatus({
      ...orderStatus,
      orderIndex
    })
  }
  // 点击按照价格排序
  const orderByPrice = () => {
    // 1 不是按照价格排序 点击 切换到价格排序 价格 升序排序
    // 2 按照价格排序  切换升序还是降序
    if (orderStatus.orderIndex !== 1) {
      setOrderStatus({
        orderIndex: 1,
        upDown: 0
      })
    } else {
      // 切换升序还是降序
      if (orderStatus.upDown === 0) {
        setOrderStatus({
          orderIndex: 1,
          upDown: 1
        })
      } else {
        setOrderStatus({
          orderIndex: 1,
          upDown: 0
        })
      }
    }
  }

  const [items, setItems] = useState<any[]>([]);
  const fetchItems = () => {
    getItems({
      categoryId: searchParams.get('cateId'),
      orderBy: order
    }).then(res => {
      if (res.data.code === 0) {
        setItems(res.data.data.result)
      }
    })
  }
  useEffect(() => {
    fetchItems()
  }, [order])
  return (
    <div className='itemLists'>
      <CommonHead title='商品列表' />
      <div className="order-bar">
        <div
          onClick={() => { orderHandler(0) }}
          className={`order sale ${orderStatus.orderIndex === 0 ? 'active' : ''}`}>
          <span>销量</span>
        </div>
        <div
          onClick={orderByPrice}
          className={`order price ${orderStatus.orderIndex === 1 ? 'active' : ''}`}>
          <span>价格</span>
          <div className={`angle up ${(orderStatus.orderIndex === 1 && orderStatus.upDown === 0) ? 'active' : ''}`}></div>
          <div className={`angle down ${(orderStatus.orderIndex === 1 && orderStatus.upDown === 1) ? 'active' : ''}`}></div>
        </div>
        <div
          onClick={() => { orderHandler(2) }}
          className={`order new ${orderStatus.orderIndex === 2 ? 'active' : ''}`}>
          <span>新品</span>
        </div>
      </div>
      <div className="container">
        <Items items={items}/>
      </div>
    </div>
  );
}
